<?php

namespace App\Console\Commands;

use App\Library\Logger;
use App\Models\CityModel;
use App\Models\Customer;
use App\Models\Customer\User;
use App\Models\DeptModel;
use App\Repositories\Customer\UserRepo;
use App\Repositories\CustomerRepo;
use Carbon\Carbon;
use Illuminate\Console\Command;
use PhpOffice\PhpSpreadsheet\IOFactory;
use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet;

class ImportCustomer extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'import:customer';

    private $logger;

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '导入客户信息';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->logger = new Logger('commands/import_customer');
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        $bench = new \Ubench();
        $bench->start();

        $this->truncateOldData();
        $this->importCustomers();

        $bench->end();
        $this->logger->debug("time used: " . $bench->getTime());
        $this->logger->debug("memory used: " . $bench->getMemoryUsage());
    }

    // 清除老旧数据
    private function truncateOldData()
    {
        User::query()->truncate();
        Customer::query()->truncate();
    }

    private function importCustomers()
    {
        $file = public_path('resources/customers/') . 'customers.xlsx';
        if (!is_file($file)) {
            $this->logger->error("file is not exist!");
            return;
        }
        $reader = IOFactory::createReader('Xlsx');
        $reader->setReadDataOnly(true);

        $spreadsheet = $reader->load($file);
        $titles = $spreadsheet->getSheetNames();
        $worksheets = $spreadsheet->getAllSheets();
        foreach ($worksheets as $index => $worksheet) {
            if (!$index) {
                continue;
            }
            $currentSheetName = str_replace('年', '', $titles[$index] ?? ''); // year
            $this->handleSheetItem($worksheet, $currentSheetName);
        }
    }

    /**
     * 获取客户数据，客户编号自动生成
     *
     * @param Worksheet $sheet
     * @param $year
     */
    private function handleSheetItem(Worksheet $sheet, $year)
    {
        $this->logger->info("read and set customer data, year: {$year}");
        $rowCount = $sheet->getHighestRow();
        if ($rowCount < 2) {
            return;
        }
        for ($i = 2; $i <= $rowCount; $i++) {
            $customerName = $sheet->getCellByColumnAndRow(2, $i)->getValue() ?? '';
            $customerName = trim($customerName);
            if (!$customerName) {
                continue;
            }
            $customerShortName = $sheet->getCellByColumnAndRow(3, $i)->getValue() ?? '';
            $customerUserName = $sheet->getCellByColumnAndRow(4, $i)->getValue() ?? '';
            $customerUserPhone = $sheet->getCellByColumnAndRow(5, $i)->getValue() ?? '';
            $province = $sheet->getCellByColumnAndRow(6, $i)->getValue() ?? '';
            $city = $sheet->getCellByColumnAndRow(7, $i)->getValue() ?? '';
            $county = $sheet->getCellByColumnAndRow(8, $i)->getValue() ?? '';

            $provinceObj = CityModel::byName($province)->first();
            $provinceId = $provinceObj->id ?? 0;
            $provinceName = $provinceObj->name ?? '';

            $cityObj = CityModel::byPid($provinceId)->byName($city)->first();
            $cityId = $cityObj->id ?? 0;
            $cityName = $cityObj->name ?? '';

            $countyObj = CityModel::byPid($cityId)->byName($county)->first();
            $countyId = $countyObj->id ?? 0;
            $countyName = $countyObj->name ?? '';

            $address = $sheet->getCellByColumnAndRow(9, $i)->getValue() ?? '';

            // 客户行业
            $industry = $sheet->getCellByColumnAndRow(11, $i)->getValue() ?? '';
            $contactAt = trim($sheet->getCellByColumnAndRow(12, $i)->getValue() ?? '');
            if ($contactAt) {
                try {
                    $contactAt = Carbon::parse($contactAt)->toDateString();
                } catch (\Exception $e) {
                    $contactAt = '';
                }
            }
            // 服务网点
            $department = str_replace('区', '', $sheet->getCellByColumnAndRow(13, $i)->getValue() ?? '');
            $departmentObj = DeptModel::byName($department)->first();
            if (empty($departmentObj)) {
                $latestDept = DeptModel::query()->orderByDesc('id')->first();
                $deptModelData = [
                    'name' => $department,
                    'code' => intval($latestDept->code ?? '') + 1,
                    'manager_id' => $latestDept->manager_id ?? 0,
                    'fullname' => $department,
                    'note' => '',
                    'type' => $latestDept->type ?? 0,
                    'pid' => $latestDept->pid ?? 0,
                    'sort' => intval($latestDept->sort ?? 0) + 1,
                    'create_user' => $latestDept->create_user ?? 0,
                    'mark' => 1
                ];
                $departmentObj = new DeptModel();
                $departmentObj->fill($deptModelData);
                $departmentObj->saveOrFail();
            }
            $departmentId = $departmentObj->id;
            $departmentName = $departmentObj->name;

            // customer user insert
            $customerUser = User::byName($customerUserName)->byPhone($customerUserPhone)->first();
            if (empty($customerUser)) {
                $customerUserModelData = [
                    'name' => $customerUserName,
                    'gender' => UserRepo::GENDER_MALE_CODE,
                    'phone' => $customerUserPhone,
                    'office_phone' => $customerUserPhone,
                    'province_id' => $provinceId,
                    'province_name' => $provinceName,
                    'city_id' => $cityId,
                    'city_name' => $cityName,
                    'county_id' => $countyId,
                    'county_name' => $countyName,
                    'address' => $address,
                    'status' => 1,
                    'create_user_id' => 1
                ];
                $customerUser = new User();
                $customerUser->fill($customerUserModelData);
                $customerUser->saveOrFail();
            }
            $customerUserId = $customerUser->id;

            $customerData = [
                'parent_id' => 0,
                'customer_number' => CustomerRepo::generateCustomerNumber(0),
                'name' => $customerName,
                'customer_user_id' => $customerUserId,
                'short_name' => $customerShortName,
                'customer_type_name' => '',
                'entry_type_name' => '',
                'tag_name' => '',
                'industry_name' => $industry,
                'safe_level' => '',
                'source' => '',
                'department_id' => $departmentId,
                'department_name' => $departmentName,
                'owner_id' => $departmentObj->manager->id ?? 0,
                'owner_name' => $departmentObj->manager->realname ?? '',
                'province_id' => $provinceId,
                'province_name' => $provinceName,
                'city_id' => $cityId,
                'city_name' => $cityName,
                'county_id' => $countyId,
                'county_name' => $countyName,
                'address' => $address,
                'contact_at' => $contactAt,
                'service_limit' => 10,
                'status' => 1
            ];

            $customerObj = Customer::byName($customerName)->byShortName($customerShortName)->first();
            if (empty($customerObj)) {
                $customerObj = new Customer();
                $customerObj->fill($customerData);
                $customerObj->saveOrFail();
            }
            $customerId = $customerObj->id;
            $customerUser->customer_id = $customerId;
            $customerUser->customer_name = $customerName;
            $customerUser->saveOrFail();
            $this->logger->info($customerId);
        }
    }
}
